import time

from page.basepage import BasePage
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
# page/login_page.py
class LoginPage(BasePage):
    def __init__(self,driver):
        super().__init__(driver)
        self.mobile_input = (By.XPATH, "//input[contains(@placeholder,'账户名')]")
        self.code_input = (By.XPATH, "//input[contains(@placeholder,'密码')]")
        self.login_button = (By.XPATH, '//button[contains(@class,"el-button")]')
        self.body = (By.TAG_NAME, "body")

    def login(self, mobile, code):
        self.driver.get("http://localhost:8802/#/login")
        time.sleep(1)
        self.input(self.mobile_input,"****")
        self.clear_input(self.mobile_input)
        time.sleep(1)
        self.input(self.mobile_input, mobile)
        self.input(self.code_input,code)
        self.click(self.login_button)

    def login_retry(self, mobile, code, retries=3, delay=5):
        """登录方法，支持重试"""
        for attempt in range(retries):
            self.login(mobile, code)
            # 判断登录是否成功，这里可以根据实际情况修改
            if self.is_login_success():
                print(f"登录成功 (尝试 {attempt + 1}/{retries})")
                return True
            else:
                print(f"登录失败，正在重试 ({attempt + 1}/{retries})")
                time.sleep(delay)

        print(f"登录失败，重试 {retries} 次后仍失败")
        return False

    def is_login_success(self, timeout=5):
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC

        try:
            # 页面上“首页”菜单出现就说明登录成功
            WebDriverWait(self.driver, timeout).until(
                EC.visibility_of_element_located(
                    (By.XPATH, '//li[contains(@class,"el-menu-item") and contains(@class,"is-active")]')
                )
            )
            return True
        except:
            return False
